package message_api

import (
	"ginBolg/global"
	"ginBolg/models"
	"ginBolg/models/res"
	"ginBolg/utils/jwt"
	"github.com/gin-gonic/gin"
	"time"
)

type Message struct {
	SendUserId       uint      `json:"sendUserId"`
	SendUserNickName string    `json:"sendUserNickName"`
	SendUserAvatar   string    `json:"sendUserAvatar"`
	RevUserId        uint      `json:"revUserId"`
	RevUserNickName  string    `json:"revUserNickName"`
	RevUserAvatar    string    `json:"revUserAvatar"`
	Content          string    `json:"content"`
	CreateAt         time.Time `json:"createAt"`
	MessageCount     int       `json:"messageCount"`
}

type MessageGroup map[uint]*Message

func (MessageApi) MessageListView(c *gin.Context) {
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwt.CustomClaims)
	var messageGroup = MessageGroup{}
	var messageList []models.MessageModel
	var messages []Message
	global.DB.Order("create_at desc").Find(&messageList, "send_user_id = ? or rev_user_id = ?", claims.UserId, claims.UserId)

	for _, model := range messageList {
		message := Message{
			SendUserId:       model.SendUserID,
			SendUserNickName: model.SendUserNickName,
			SendUserAvatar:   model.SendUserAvatar,
			RevUserId:        model.RevUserID,
			RevUserNickName:  model.RevUserNickName,
			RevUserAvatar:    model.RevUserAvatar,
			Content:          model.Content,
			CreateAt:         model.CreateAt,
			MessageCount:     1,
		}
		idNum := model.SendUserID + model.RevUserID
		val, ok := messageGroup[idNum]
		if !ok {
			messageGroup[idNum] = &message
			continue
		}
		message.MessageCount = val.MessageCount + 1
		messageGroup[idNum] = &message
	}
	for _, message := range messageGroup {
		messages = append(messages, *message)
	}
	res.OkWithData(messages, c)
	return
}
